package org.rslai.tcedit.web.user;

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.hibernate.validator.InvalidStateException;
import org.hibernate.validator.InvalidValue;
import org.rslai.tcedit.domain.User;
import org.rslai.tcedit.domain.UserDetails;
import org.rslai.tcedit.exception.ApplicationException;
import org.rslai.tcedit.security.SecurityUtil;
import org.rslai.tcedit.util.HttpUtil;
import org.rslai.tcedit.web.core.AbstractMvcController;

/**
 * 修改个人资料
 * 
 * @author rslai
 * 
 * @spring.bean name="/user/profile.jspx"
 */
public class ProfileController extends AbstractMvcController {

	@Override
	public Map<String, Object> getModel(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String message = "";
		User user = (User) userService.query(SecurityUtil.getCurrentUsername());
		Map<String, Object> map = new HashMap<String, Object>();

		if(request.getMethod().equals("POST")) {
			// update:
			User postUser = (User) HttpUtil.createFormBean(request, User.class);
			user.setRealName(postUser.getRealName());
			user.setEmail(postUser.getEmail());

			UserDetails postUserDetail = (UserDetails) HttpUtil.createFormBean(request, UserDetails.class);
			UserDetails userDetails = user.getUserDetails();
			userDetails.setAddress(postUserDetail.getAddress());
			userDetails.setZip(postUserDetail.getZip());
			userDetails.setTelephone(postUserDetail.getTelephone());
			userDetails.setMobile(postUserDetail.getMobile());
			userDetails.setEducation(postUserDetail.getEducation());
			userDetails.setEmployment(postUserDetail.getEmployment());
			userDetails.setProject(postUserDetail.getProject());

			try {
				userService.update(user, userDetails, user.getRoles());
				message = "更新成功！";
			}
			catch (Exception e) {
				map.put("error", convertException(e));
			}
		}

		map.put("user", user);
		map.put("message", message);
		return map;
	}

	@Override
	public String getView(HttpServletRequest request, HttpServletResponse response) {
		return "/user/profile.htm";
	}

	private String convertException(Exception e) throws Exception {
		if (e instanceof ApplicationException) {
			return e.getMessage();
		} else if (e instanceof InvalidStateException) {
			StringBuffer sb = new StringBuffer(128);
			InvalidValue[] ivs = ((InvalidStateException) e).getInvalidValues();
			for (InvalidValue iv : ivs)
				sb.append(iv.getMessage()).append("<br/>");
			return sb.toString();
		}
		throw e;
	}

}
